//
//  YuanXinToastManager.m
//  YuanXinKit
//
//  Created by 晏德智 on 2017/4/11.
//  Copyright © 2017年 晏德智. All rights reserved.
//

#import "YuanXinToastManager.h"
#import "MessageBarManager.h"
#import "MessageBarDefaultOptions.h"
#import "UIColor+HexString.h"

@implementation YuanXinToastManager

@synthesize bridge = _bridge;

RCT_EXPORT_MODULE();

- (dispatch_queue_t)methodQueue
{
    return dispatch_get_main_queue();
}

RCT_EXPORT_METHOD(showNavigationBar:(NSDictionary *)options
                  resolver:(RCTPromiseResolveBlock)resolve
                  rejecter:(RCTPromiseRejectBlock)reject){
    
    NSDictionary *imageData = options[@"imageSource"];
    if(imageData){
        BOOL  packagerAsset = [RCTConvert BOOL:imageData[@"__packager_asset"]];
        if(packagerAsset){
            UIImage *image = [RCTConvert UIImage:imageData];
            [self privateShowMessageBar:options image:image resolver:resolve rejecter:reject];
        }else{
            __block  RCTPromiseRejectBlock failure = nil;
            if(reject){
                failure =  [reject copy];
            }
            __weak typeof (self) weakSelf =  self;
            RCTImageLoaderCompletionBlock loaderCompletionBlock =^(NSError *error, UIImage *image) {
                RCTExecuteOnMainQueue(^{
                    if(!error){
                        [weakSelf privateShowMessageBar:options image:image resolver:resolve rejecter:failure];
                    }else{
                        if(failure){
                            failure(@(error.code).stringValue,[error localizedDescription],error);
                        }
                    }
                });
            };
            
            NSURLRequest *imageReauest = [RCTConvert NSURLRequest:imageData];
            NSInteger padding = [RCTConvert NSInteger:options[@"padding"]];
            CGFloat height = 44 - (2 * padding);
            CGSize  size = CGSizeMake(height, height);
            //[NSURLRequest requestWithURL:[NSURL URLWithString:imageUrl]];
#if __has_include(<React/RCTImageLoader.h>)
            [_bridge.imageLoader loadImageWithURLRequest:imageReauest
                                                    size:size
                                                   scale:1
                                                 clipped:YES
                                              resizeMode:RCTResizeModeStretch
                                           progressBlock:nil
                                        partialLoadBlock:nil
                                         completionBlock:loaderCompletionBlock];
#else
            [_bridge.imageLoader loadImageWithURLRequest:imageReauest
                                                    size:size
                                                   scale:1
                                                 clipped:YES
                                              resizeMode:UIViewContentModeScaleToFill
                                           progressBlock:nil
                                         completionBlock:loaderCompletionBlock];
#endif
        }
    }else {
        [self privateShowMessageBar:options image:nil resolver:resolve rejecter:reject];
    }
}

RCT_EXPORT_METHOD(showStatusBar:(NSDictionary *)options
                  resolver:(RCTPromiseResolveBlock)resolve
                  rejecter:(RCTPromiseRejectBlock)reject){
    
    NSMutableDictionary *coptions = [@{
                                       kCRToastNotificationTypeKey:@(CRToastTypeStatusBar),
                                       kCRToastNotificationPresentationTypeKey:@(CRToastPresentationTypePush),
                                       kCRToastUnderStatusBarKey: @(NO),
                                       kCRToastAnimationInTypeKey:@(CRToastAnimationTypeLinear),
                                       kCRToastAnimationOutTypeKey:@(CRToastAnimationTypeGravity),
                                       kCRToastAnimationInDirectionKey:@(0),
                                       kCRToastAnimationOutDirectionKey:@(0)
                                       } mutableCopy];
    
    __block NSString  *tagID =  [RCTConvert NSString:options[@"tagID"]]?:[[NSUUID new].UUIDString stringByReplacingOccurrencesOfString:@"-" withString:@""];
    coptions[kCRToastIdentifierKey] = tagID;
    
    NSString *message = [options objectForKey:@"message"];
    if(message){
        [coptions setObject:message forKey:kCRToastTextKey];
        NSInteger alignment = [RCTConvert NSInteger:options[@"textAlignment"]] ;
        coptions[kCRToastTextAlignmentKey] = @([self getTextAlignment:alignment]);
    }
    
    NSInteger timeInterval = [RCTConvert NSInteger:options[@"timeInterval"]];
    coptions[kCRToastTimeIntervalKey] = @(timeInterval);
    NSInteger padding = [RCTConvert NSInteger:options[@"padding"]];
    coptions[kCRToastNotificationPreferredPaddingKey] = @(padding);
    NSString *colorStr = options[@"backgroundColor"];
    UIColor *backgroundColor = nil;
    if(colorStr){
        backgroundColor = [UIColor colorWithHexString:colorStr];
    }else{
        backgroundColor = [UIColor colorWithRed:0.22 green:0.80 blue:0.46 alpha:1.00];;
    }
    coptions[kCRToastBackgroundColorKey] = backgroundColor;
    
    colorStr = options[@"textColor"];
    UIColor *textColor = nil;
    if(colorStr){
        textColor = [UIColor colorWithHexString:colorStr];
    }else{
        textColor = [UIColor whiteColor];
    }
    coptions[kCRToastTextColorKey] = textColor;
    
    UIFont *textFont = [RCTConvert UIFont:options[@"textFont"]];
    if(textFont){
        coptions[kCRToastFontKey] = textFont;
    }
    
    colorStr = options[@"desTextColor"];
    UIColor *desTextColor = nil;
    if(colorStr){
        desTextColor = [UIColor colorWithHexString:colorStr];
    }else{
        desTextColor = [UIColor whiteColor];
    }
    coptions[kCRToastSubtitleTextColorKey] = desTextColor;
    
    BOOL forceUserInteraction = [RCTConvert BOOL:options[@"forceUserInteraction"]];
    __block BOOL  isUserTapped = NO;
    if(forceUserInteraction){
        coptions[kCRToastForceUserInteractionKey] = @(forceUserInteraction);
        coptions[kCRToastInteractionRespondersKey] = @[[CRToastInteractionResponder
                                                        interactionResponderWithInteractionType:CRToastInteractionTypeTap
                                                        automaticallyDismiss:YES
                                                        block:^(CRToastInteractionType interactionType){
                                                            isUserTapped = YES;
                                                            NSLog(@"Dismissed with %@ interaction", NSStringFromCRToastInteractionType(interactionType));
                                                        }]];
        
    }
    
    [MessageBarManager showNotificationWithOptions:coptions
                                    apperanceBlock:nil
                                   completionBlock:^(void) {
                                       if(resolve){
                                           resolve(@{
                                                     @"isUserTapped":[NSNumber numberWithBool:isUserTapped],
                                                     @"tagID" : tagID
                                                     });
                                       }
                                   }];
    
}


RCT_EXPORT_METHOD(showNotifications:(NSDictionary *)options
                  resolver:(RCTPromiseResolveBlock)resolve
                  rejecter:(RCTPromiseRejectBlock)reject){
    
    UIImage *iconImage = nil;
    NSString *style = options[@"style"];
    if(style){
        NSString *imageName = [NSString stringWithFormat:@"YuanXinKitResource.bundle/%@.png",style];
        iconImage = [UIImage imageNamed:imageName];
    }
    
    [self privateShowMessageBar:options image:iconImage resolver:resolve rejecter:reject];
}


- (void)privateShowMessageBar:(NSDictionary *)options
                       image :(UIImage *) image
                     resolver:(RCTPromiseResolveBlock)resolve
                     rejecter:(RCTPromiseRejectBlock)reject{
    
    NSMutableDictionary *coptions = [@{
                                       kCRToastNotificationTypeKey:@(CRToastTypeNavigationBar),
                                       kCRToastNotificationPresentationTypeKey:@(CRToastPresentationTypeCover),
                                       kCRToastUnderStatusBarKey: @(YES),
                                       kCRToastAnimationInTypeKey:@(CRToastAnimationTypeLinear),
                                       kCRToastAnimationOutTypeKey:@(CRToastAnimationTypeLinear),
                                       kCRToastAnimationInDirectionKey:@(CRToastAnimationDirectionTop),
                                       kCRToastAnimationOutDirectionKey:@(CRToastAnimationDirectionTop)
                                       } mutableCopy];
    
    __block NSString  *tagID =  [RCTConvert NSString:options[@"tagID"]]?:[[NSUUID new].UUIDString stringByReplacingOccurrencesOfString:@"-" withString:@""];
    coptions[kCRToastIdentifierKey] = tagID;
    
    NSString *message = [options objectForKey:@"title"];
    if(message){
        coptions[kCRToastTextKey] = message;
        NSInteger alignment = [RCTConvert NSInteger:options[@"textAlignment"]] ;
        coptions[kCRToastTextAlignmentKey] = @([self getTextAlignment:alignment]);
    }
    
    NSString *descr = [options objectForKey:@"description"];
    if(descr){
        coptions[kCRToastSubtitleTextKey] = descr;
        NSInteger alignment = [RCTConvert NSInteger:options[@"desTextAlignment"]] ;
        coptions[kCRToastSubtitleTextAlignmentKey] = @([self getTextAlignment:alignment]);
    }
    
    NSInteger timeInterval = [RCTConvert NSInteger:options[@"timeInterval"]];
    coptions[kCRToastTimeIntervalKey] = @(timeInterval);
    
    NSInteger padding = [RCTConvert NSInteger:options[@"padding"]];
    coptions[kCRToastNotificationPreferredPaddingKey] = @(padding);
    
    NSString *colorStr = options[@"backgroundColor"];
    UIColor *backgroundColor = nil;
    if(colorStr){
        backgroundColor = [UIColor colorWithHexString:colorStr];
    }else{
        backgroundColor = [UIColor colorWithRed:0.22 green:0.80 blue:0.46 alpha:1.00];;
    }
    coptions[kCRToastBackgroundColorKey] = backgroundColor;
    
    colorStr = options[@"textColor"];
    UIColor *textColor = nil;
    if(colorStr){
        textColor = [UIColor colorWithHexString:colorStr];
    }else{
        textColor = [UIColor whiteColor];
    }
    coptions[kCRToastTextColorKey] = textColor;
    
    colorStr = options[@"desTextColor"];
    UIColor *desTextColor = nil;
    if(colorStr){
        desTextColor = [UIColor colorWithHexString:colorStr];
    }else{
        desTextColor = [UIColor whiteColor];
    }
    coptions[kCRToastSubtitleTextColorKey] = desTextColor;
    
    UIFont *textFont = [RCTConvert UIFont:options[@"textFont"]];
    if(textFont){
        coptions[kCRToastFontKey] = textFont;
    }
    
    UIFont *desTextFont = [RCTConvert UIFont:options[@"desTextFont"]];
    if(desTextFont){
        coptions[kCRToastSubtitleFontKey] = desTextFont;
    }
    
    if(image){
        coptions[kCRToastImageKey] = image;
        NSInteger imageAlignment = [RCTConvert NSInteger:options[@"imageAlignment"]] ;
        coptions[kCRToastTextAlignmentKey] = @(imageAlignment);
        colorStr = options[@"imageColor"];
        if(colorStr){
            UIColor *imageTintColor = [UIColor colorWithHexString:colorStr];
            if(imageTintColor){
                coptions[kCRToastImageTintKey] = imageTintColor;
            }
        }
    }
    
    BOOL showActivityIndicator = [RCTConvert BOOL:options[@"showActivityIndicator"]];
    if(showActivityIndicator){
        coptions[kCRToastShowActivityIndicatorKey] = @(YES);
        NSInteger activityIndicatorAlignment = [RCTConvert NSInteger:options[@"activityIndicatorAlignment"]] ;
        coptions[kCRToastActivityIndicatorAlignmentKey] = @(activityIndicatorAlignment);
    }
   
    BOOL forceUserInteraction = [RCTConvert BOOL:options[@"forceUserInteraction"]];
    if(forceUserInteraction){
        coptions[kCRToastForceUserInteractionKey] = @(forceUserInteraction);
    }
    
    __block BOOL  isUserTapped = NO;
    coptions[kCRToastInteractionRespondersKey] = @[[CRToastInteractionResponder
                                                    interactionResponderWithInteractionType:CRToastInteractionTypeTap
                                                    automaticallyDismiss:YES
                                                    block:^(CRToastInteractionType interactionType){
                                                        isUserTapped  = YES;
                                                    }]];
    
    __block RCTPromiseResolveBlock successBlock = [resolve copy];
    [MessageBarManager showNotificationWithOptions:coptions
                                    apperanceBlock:nil
                                   completionBlock:^(void) {
                                       if(successBlock){
                                           successBlock(@{
                                                     @"isUserTapped":[NSNumber numberWithBool:isUserTapped],
                                                     @"tagID" : tagID
                                                     });
                                       }
                                   }];
    
}

- (NSTextAlignment)getTextAlignment:(NSInteger)alignment{
    
    NSTextAlignment result = NSTextAlignmentLeft;
    switch (alignment) {
        case 1:
            result = NSTextAlignmentCenter;
            break;
        case 2:
            result = NSTextAlignmentRight;
            break;
        default:
            result = NSTextAlignmentLeft;
            break;
    }
    
    return result;
}

@end
